package com.cxb.demotest.mq.rocketmq.send_style;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;


/**
 * 异步发送消息，一般用于不用等待消息结果的场景，适合于发送的数据量大，可以容忍之后拿到结果。
 * @author Xb
 */
public class AsyncProducer {
    public static void main(String[] args) throws Exception {
        // 实例化消息生产者
        DefaultMQProducer producer = new DefaultMQProducer("group_test");

        // 设置nameserver的地址
        producer.setNamesrvAddr("127.0.0.1:9876");

        // 启动producer实例
        producer.start();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            // 创建消息，执行topic，tag，消息体
            Message message = new Message(
                    "topic_test",
                    "tag_test",
                    "order_0001",
                    "Hello, RockerMQ!".getBytes(RemotingHelper.DEFAULT_CHARSET)
            );
            // sendCallback接受异步发送的结果
            producer.send(message, new SendCallback() {
                        @Override
                        public void onSuccess(SendResult sendResult) {
                            System.out.printf("%s%n", sendResult);
                        }

                        @Override
                        public void onException(Throwable e) {
                            System.out.printf("%-10d Exception %s %n", index, e);
                        }
                    }
            );
        }

        Thread.sleep(10*1000);
        // 不再发送消息，关闭生产者实例
        producer.shutdown();

    }

}
